// 小项目实践
// 1.在socket上监听TCP连接
// 2.解析少量的HTTP请求
// 3.创建一个合适的HTTP相应
// 4.使用线程池改进服务器的吞吐量
// 5.停机和清理

use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::thread;
use std::time::Duration;
use hello::ThreadPool;

fn main() {
    // 监听TCP
    let listerner = TcpListener::bind("127.0.0.1:8080").unwrap();
    let pool = ThreadPool::new(4); // 多线程
    for stream in listerner.incoming().take(2) {
        let stream = stream.unwrap();
        pool.execute(|| { // 多线程
            handle_connection(stream);
        });
    }
    println!("shutting down");
}

fn handle_connection(mut stream: TcpStream) {
    let mut buffer = [0; 512];
    stream.read(&mut buffer).unwrap();
    // 请求
    // Method Request-URI HTTP-Version CRLF
    // headers CRLF
    // message-body
    // 响应
    // HTTP-Version Status-Code Reason-Phrase CRLF
    // headers CRLF
    // message-body

    let get = b"GET / HTTP/1.1\r\n"; // b是字节字符串的语法
    let sleep = b"GET /sleep HTTP/1.1\r\n";
    let (status_line, filename) = if buffer.starts_with(get) {
        ("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
    } else if buffer.starts_with(sleep) {
        thread::sleep(Duration::from_secs(5));
        ("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
    } else {
        ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
    };

    let contents = fs::read_to_string(filename).unwrap();
    let response = format!("{}{}", status_line, contents);

    stream.write(response.as_bytes()).unwrap();
    stream.flush().unwrap();
    // @todo很奇怪客户端接收不到数据

    // println!("{}", String::from_utf8_lossy(&buffer[..]));
}
